package org.lanyu.springainovel.common.listener;

import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.common.event.UserChangeEvent;
import org.lanyu.springainovel.common.service.UserCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 用户变更事件监听器
 * 监听用户变更事件，更新缓存
 */
@Component
@Slf4j
public class UserChangeListener {
    
    @Autowired
    private UserCacheService userCacheService;
    
    /**
     * 处理用户变更事件
     * 
     * @param event 用户变更事件
     */
    @EventListener
    public void handleUserChange(UserChangeEvent event) {
        User user = event.getUser();
        UserChangeEvent.ChangeType changeType = event.getChangeType();
        
        log.debug("处理用户变更事件: 用户ID={}, 用户名={}, 变更类型={}", 
                user.getId(), user.getUsername(), changeType);
        
        switch (changeType) {
            case CREATE:
            case UPDATE:
                // 更新或创建用户时，更新缓存
                userCacheService.updateUser(user);
                break;
            case DELETE:
                // 删除用户时，从缓存中移除
                userCacheService.evictUser(user.getId());
                userCacheService.evictUser(user.getUsername());
                break;
            default:
                log.warn("未知的用户变更类型: {}", changeType);
                break;
        }
    }
}